package com.dnjn.happiness.common.config.ext;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.Validate;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

/**
 * @author Amber
 * @version v0.0.1
 * @date 11/15/2021 3:18 PM
 */
@Slf4j
@Component
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {

    private static ApplicationContext ctx = null;

    public SpringContextHolder() {
    }

    @Override
    public void destroy() throws Exception {
        log.info("clean ctx...");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ctx = applicationContext;
    }

    public static ApplicationContext getContext() {
        return ctx;
    }

    public static <T> T getBean(String name) {
        assertContentInjected();
        return (T) ctx.getBean(name);
    }

    public static <T> T getBean(Class<T> requiredType) {
        assertContentInjected();
        return ctx.getBean(requiredType);
    }

    public static <T> T getBean(String name, Class<T> requiredType) {
        return ctx.getBean(name, requiredType);
    }

    public static String[] getBeanDefinitionNames() {
        return ctx.getBeanDefinitionNames();
    }

    public static String i18n(String key, Object... args) {
        return ctx.getMessage(key, args, LocaleContextHolder.getLocale());
    }

    private static void assertContentInjected() {
        Validate.validState(ctx != null, "ctx attribute net injected,Please inject SpringContextHolder.",
                new Object[0]);
    }
}